
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.DefaultListModel;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Arthur
 */
public class ChatPrivado extends javax.swing.JFrame {

    private Socket conexao;
    private String nickname, meuNick;
    private PrintStream saida;
    private DefaultListModel modelListaMensagensPrivadas = new DefaultListModel();
    private Player player;
    private File file;
    private Recebedor recebedor;

    public ChatPrivado() {
        initComponents();
    }

    public ChatPrivado(Socket conexao, String nickname, String meuNick, Recebedor recebedor) throws IOException {
        initComponents();
        listaMensagensPrivadas.setModel(modelListaMensagensPrivadas);
        this.conexao = conexao;
        this.nickname = nickname;
        this.meuNick = meuNick.toUpperCase();
        this.recebedor = recebedor;
        saida = new PrintStream(conexao.getOutputStream());
        labelTitulo.setText("Conversa com " + nickname);
        this.setTitle(nickname + " - Chat");
    }

    public void play() {
        if (!checkSom.isSelected()) {
            try {
                this.file = new File("bip_privado.mp3");
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                this.player = new Player(bis);
                this.player.play();
            } catch (FileNotFoundException | JavaLayerException e) {
                System.out.println("Problema ao tocar ");
            }
        }
    }

    public void adicionarMensagemPrivada(String s, String nome) {
        if (nome.equals(this.nickname)) {
            modelListaMensagensPrivadas.add(modelListaMensagensPrivadas.size(), horaAtual() + s);
            listaMensagensPrivadas.ensureIndexIsVisible(listaMensagensPrivadas.getModel().getSize() - 1);
            play();
        }
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String horaAtual() {
        String formatoHora = "HH:mm:ss";
        Date agora = new Date();
        SimpleDateFormat formata = new SimpleDateFormat(formatoHora);
        return "[" + formata.format(agora) + "] ";
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelTitulo = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaMensagensPrivadas = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        mensagem = new javax.swing.JTextArea();
        checkTeclaEnter = new javax.swing.JCheckBox();
        botaoSair = new javax.swing.JButton();
        botaoEnviar = new javax.swing.JButton();
        checkSom = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        labelTitulo.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        labelTitulo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/user.png"))); // NOI18N
        labelTitulo.setText("Conversa com");

        jScrollPane1.setViewportView(listaMensagensPrivadas);

        mensagem.setColumns(20);
        mensagem.setRows(5);
        mensagem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                mensagemKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(mensagem);

        checkTeclaEnter.setText("Desativar envio com a tecla Enter");

        botaoSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/sair.png"))); // NOI18N
        botaoSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoSairActionPerformed(evt);
            }
        });

        botaoEnviar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/enviar.png"))); // NOI18N
        botaoEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoEnviarActionPerformed(evt);
            }
        });

        checkSom.setText("Desativar sons");
        checkSom.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                checkSomMouseClicked(evt);
            }
        });

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Superior.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(142, 142, 142)
                .addComponent(jLabel2)
                .addGap(118, 118, 118))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(labelTitulo)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(checkTeclaEnter)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(checkSom)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botaoSair, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botaoEnviar, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelTitulo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(botaoEnviar)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(checkTeclaEnter)
                    .addComponent(checkSom)
                    .addComponent(botaoSair))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mensagemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mensagemKeyPressed
        // TODO add your handling code here:
        int key = evt.getKeyCode();
        if (!checkTeclaEnter.isSelected()) {
            if (key == KeyEvent.VK_ENTER) {
                if (!mensagem.getText().trim().equals("")) {
                    modelListaMensagensPrivadas.add(modelListaMensagensPrivadas.size(), horaAtual() + meuNick + " escreveu: " + mensagem.getText().trim());
                    saida.println("6_" + mensagem.getText().trim() + "&" + nickname);
                    mensagem.setText(null);
                }
            }
        }
    }//GEN-LAST:event_mensagemKeyPressed

    private void botaoSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoSairActionPerformed
        saida.println("6_%&" + nickname);
        ArrayList<ChatPrivado> listaChats = recebedor.getListaChats();
        listaChats.remove(this);
        recebedor.setListaChats(listaChats);
        dispose();
    }//GEN-LAST:event_botaoSairActionPerformed

    private void botaoEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEnviarActionPerformed

        if (!mensagem.getText().trim().equals("")) {
            modelListaMensagensPrivadas.add(modelListaMensagensPrivadas.size(), horaAtual() + meuNick + " escreveu: " + mensagem.getText().trim());
            saida.println("6_" + mensagem.getText().trim() + "&" + nickname);
            mensagem.setText("");
        }
    }//GEN-LAST:event_botaoEnviarActionPerformed

    private void checkSomMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkSomMouseClicked
        // TODO add your handling code here:

    }//GEN-LAST:event_checkSomMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ChatPrivado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ChatPrivado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ChatPrivado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ChatPrivado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChatPrivado().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoEnviar;
    private javax.swing.JButton botaoSair;
    private javax.swing.JCheckBox checkSom;
    private javax.swing.JCheckBox checkTeclaEnter;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labelTitulo;
    private javax.swing.JList listaMensagensPrivadas;
    private javax.swing.JTextArea mensagem;
    // End of variables declaration//GEN-END:variables
}
